// ignore_for_file: prefer_const_constructors

import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../../common/models/index.dart';
import '../../../../common/style/index.dart';
import '../../../../common/utils/index.dart';
import '../../../../common/widgets/index.dart';
import '../index.dart';

class BannerAndAppsWidget extends GetView<DefaultIndexController> {
  const BannerAndAppsWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.only(
              bottomLeft: Radius.circular(10),
              bottomRight: Radius.circular(10)),
          color: Theme.of(context).colorScheme.surface,
        ),
        child: Padding(
            padding: const EdgeInsets.only(
                left: 15.0, right: 15.0, top: 15.0, bottom: 10.0),
            child: LayoutBuilder(builder: (context, constraints) {
              if (constraints.maxWidth > 600) {
                return horizontalLayout(context);
              } else {
                return verticalLayout(context);
              }
            })));
  }

  Widget horizontalLayout(BuildContext context) {
    return Row(
      children: [
        Expanded(child: _bannerView(context)),
        const SizedBox(height: 5),
        Expanded(child: _appListView()),
      ],
    );
  }

  Widget verticalLayout(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        _bannerView(context),
        const SizedBox(height: 5),
        _appListView()
      ],
    );
  }

  /// 应用快捷键列表
  Widget _appListView() {
    return LayoutBuilder(builder: (context, constraints) {
      final cWidth = constraints.maxWidth;
      const double itemWidth = 96;
      const itemHeight = 60;
      final itemAxisCount = O2Utils.calculateItemsPerRow(cWidth, itemWidth);
      const ratio = itemWidth / itemHeight;
      OLogger.d(
          'layout Width:$cWidth, itemWidth: $itemWidth, itemHeight: $itemHeight, itemAxisCount： $itemAxisCount ratio: $ratio');
      return Obx(() => GridView.builder(

          ///Container跟随GridView内容变化高度, shrinkWrap:true;
          shrinkWrap: true,

          ///取消滚动效果physics: NeverScrollableScrollPhysics();
          physics: const NeverScrollableScrollPhysics(),
          itemCount: controller.state.myAppList.length,
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: itemAxisCount,
            mainAxisSpacing: 10,
            crossAxisSpacing: 0,
            childAspectRatio: ratio,
          ),
          itemBuilder: (context, index) {
            var app = controller.state.myAppList[index];
            return GestureDetector(
                onTap: () => controller.openApp(app),
                child: _appItemView(context, app!));
          }));
    });
  }

  

  Widget _appItemView(BuildContext context, AppFrontData element) {
    var showName = element.displayName ?? '';
    if (showName.trim().isEmpty) {
      showName = element.name ?? '';
    }
    return Column(children: [
      // Icon图标，原生应用是本地图标，门户应用是url
      O2UI.badgeView(
          element.showNumber ?? 0,
          (element.type == O2AppTypeEnum.native)
              ? AssetsImageView(
                  element.nativeEnum?.assetPath ?? 'app_task.png',
                  width: 36,
                  height: 36,
                )
              : O2UI.portalIconImage(element.portalIconUrl!)),

      Expanded(
          flex: 1,
          child: Center(
              child: Text(showName,
                  softWrap: true,
                  style: Theme.of(context).textTheme.bodyMedium)))
    ]);
  }

  /// 滚动大图
  Widget _bannerView(BuildContext context) {
    return LayoutBuilder(builder: (context, constraints) {
      OLogger.d('_bannerView Layout =======> width ${constraints.maxWidth} ');
      final double width =
          constraints.maxWidth > 600 ? 600 : constraints.maxWidth;
      final height = width / 2;
      return Obx(() => controller.state.hotpicList.isEmpty
          ? Container(height: 0)
          : SizedBox(
              width: width,
              child: CarouselSlider.builder(
                  itemCount: controller.state.hotpicList.length,
                  itemBuilder: (content, index, realIndex) {
                    HotpicData data = controller.state.hotpicList[index];
                    String? url =
                        O2ApiManager.instance.getHotPictureUrl(data.picId!);
                    if (url != null && url.isNotEmpty) {
                      Map<String, String> headers = {};
                      headers[O2ApiManager.instance.tokenName] =
                          O2ApiManager.instance.o2User?.token ?? '';
                      return GestureDetector(
                          onTap: () => controller.openHotPic(data),
                          child: Container(
                              margin: const EdgeInsets.only(
                                  left: 2, right: 2, bottom: 10),
                              child: ClipRRect(
                                  borderRadius: const BorderRadius.all(
                                      Radius.circular(5.0)),
                                  child: Stack(
                                    children: [
                                      Positioned.fill(
                                          child: Image(
                                              image: NetworkImage(url,
                                                  headers: headers),
                                              alignment: Alignment.center,
                                              height: double.infinity,
                                              width: double.infinity,
                                              fit: BoxFit.fill)),
                                      Positioned(
                                          bottom: 0,
                                          left: 0,
                                          right: 0,
                                          child: Container(
                                            padding: const EdgeInsets.symmetric(
                                                vertical: 5.0,
                                                horizontal: 10.0),
                                            color: AppColor
                                                .blackTransparentBackground,
                                            child: Text(data.title ?? '',
                                                style: TextStyle(
                                                    color: Colors.white,
                                                    fontSize: 16)),
                                          ))
                                    ],
                                  ))));
                    }
                    return const AssetsImageView('banner_default.png');
                  },
                  options: CarouselOptions(
                    height: height,
                    autoPlay: true,
                    viewportFraction: 1,
                    aspectRatio: 16 / 9,
                  ))));
    });
  }
}
